package email

import (
	"fmt"
	"net/smtp"

	"bbs/pkg/domain"

	"github.com/go-playground/validator/v10"
)

type emailService struct {
	from string
}

func NewEmailService() domain.EmailService {

	return &emailService{
		from: "lcs_shun@foxmail.com",
	}
}

func (svc *emailService) SendCaptcha(message, email string) error {
	validate := validator.New()
	if err := validate.Var(email, "email"); err != nil {
		return fmt.Errorf("invalid email address, %v", err)
	}

	auth := svc.auth(email)
	msg := svc.getCaptchaMessage(email, message)

	err := smtp.SendMail(
		"smtp.qq.com:25",
		auth,
		svc.from,
		[]string{email},
		[]byte(msg),
	)

	return err
}

func (svc *emailService) auth(email string) smtp.Auth {
	return smtp.PlainAuth("", svc.from, "ndvqyipzfqrsgihg", "smtp.qq.com")
}

func (svc *emailService) getCaptchaMessage(email, message string) string {
	subject := "邮箱验证码"
	contentType := "Content-Type: text/html; charset=UTF-8"
	msg := "From: " + svc.from + "\r\nTo: " + email +
		"\r\nSubject: " + subject + "\r\n" + contentType + "\r\n" + message
	return msg
}
